﻿if (jQuery) (function($) {

    $.extend($.fn, {
        fileGrid: function(o, h, cl) {
            // Defaults
            if (!o) var o = {};
            if (o.root == undefined) o.root = '/';
            if (o.script == undefined) o.script = '';
            if (o.loadMessage == undefined) o.loadMessage = 'Loading...';


            $.fn.fileGrid.info = {
                path: "",
                isLeaf: false,
                back: false,
                oPath: "",
                focusPath: ""
            };

            $.fn.fileGrid.reload = function(dir) {
                o.show(o.$this, escape(dir));
            }


            $(this).each(function() {

                o.show = showGrid; o.$this = $(this);

                function showGrid(c, t) {
                    $(c).empty();
                    $.post(o.script, { dir: t }, function(data) {
                        $(c).append(data);
                        bindGrid(c);
                    });
                }

                function bindGrid(t) {
                    var info = $.fn.fileGrid.info;

                    $(t).find('LI').bind("dblclick", function() {
                        var dir = $(this).children().children();
                        if (dir.hasClass('directory') || dir.hasClass('back')) {
                            info.isLeaf = false;
                            showGrid(t, escape(dir.attr('rel')));

                            if (dir.hasClass('back')) {
                                info.back = true;
                            }
                            else
                                info.back = false;

                        } else {
                            info.isLeaf = true; info.back = false;
                        }

                        info.path = dir.attr('rel');
                        info.oPath = dir.attr('orel');
                        h(info);

                        return false;
                    }).bind("click", function() {
                        var dir = $(this).children().children();
                        if (!dir.hasClass('back')) {

                            if ($(this).children("div:first").hasClass("jquery_filegrid_border_foucs")) {
                                $(this).children("div:first").removeClass("jquery_filegrid_border_foucs").attr("currselect", "false");
                            }
                            else {
                                $(this).children("div:first").addClass("jquery_filegrid_border_foucs").attr("currselect", "true");
                            }
                        }
                        info.focusPath = dir.attr('rel');
                        cl(info);
                        return false;
                    });

                }

                showGrid($(this), escape(o.root));
            });
        }
    });

})(jQuery);